const db = require('../db/dbs');
const mysql = require('mysql');

function User(openid) {
  this.openid = openid;
}

// 更新用户数据的方法
User.prototype.updateUserData = async function(dataType, newData, openid) {
  console.log('收到的新数据:',newData);
  const escapedDataType = mysql.escapeId(dataType);
  const updateQuery = `UPDATE user SET ${escapedDataType} = ? WHERE openid = ?`;
  try {
      const result = await db.query(updateQuery, [newData, openid]);
      return result;
  } catch (error) {
      throw new Error(`无法更新用户数据: ${error.message}`);
  }
};

// 获取用户数据的方法
User.prototype.getUserData = async function(dataType, openid) {
  const escapedDataType = mysql.escapeId(dataType);
  const selectQuery = `SELECT ${escapedDataType} FROM user WHERE openid = ?`;
  try {
    const rows = await db.query(selectQuery, [openid]);
    if (rows.length > 0) {
      return rows[0][dataType]; // 假设查询结果中有对应的数据类型字段
    } else {
      throw new Error(`找不到用户数据或数据类型 ${dataType}`);
    }
  } catch (error) {
    throw new Error(`无法获取用户数据: ${error.message}`);
  }
};
// 查询全部用户数据
User.prototype.getAllUsersExceptOne = async function(openid) {
  const selectQuery = `SELECT * FROM user`;
  try {
    const rows = await db.query(selectQuery, [openid]);
    return rows; // 返回所有除了传入的openid对应用户之外的用户数据
  } catch (error) {
    throw new Error(`无法获取用户数据: ${error.message}`);
  }
};

module.exports = {
  User, // 导出User构造函数
  getUserData: User.prototype.getUserData,
  updateUserData: User.prototype.updateUserData,
  getAllUsersExceptOne: User.prototype.getAllUsersExceptOne
};
